using Senparc.Weixin.Exceptions;
using Senparc.Weixin.QY.Entities;
using System;
using System.Collections.Generic;
namespace Senparc.Weixin.QY.CommonAPIs
{
	public class ProviderTokenContainer
	{
		private static Dictionary<string, ProviderTokenBag> ProviderTokenCollection = new Dictionary<string, ProviderTokenBag>(StringComparer.OrdinalIgnoreCase);
		public static void Register(string corpId, string corpSecret)
		{
			ProviderTokenContainer.ProviderTokenCollection[corpId] = new ProviderTokenBag
			{
				CorpId = corpId,
				CorpSecret = corpSecret,
				ExpireTime = DateTime.MinValue,
				ProviderTokenResult = new ProviderTokenResult()
			};
		}
		public static string TryGetToken(string corpId, string corpSecret, bool getNewToken = false)
		{
			if (!ProviderTokenContainer.CheckRegistered(corpId) || getNewToken)
			{
				ProviderTokenContainer.Register(corpId, corpSecret);
			}
			return ProviderTokenContainer.GetToken(corpId, false);
		}
		public static string GetToken(string corpId, bool getNewToken = false)
		{
			return ProviderTokenContainer.GetTokenResult(corpId, getNewToken).provider_access_token;
		}
		public static ProviderTokenResult GetTokenResult(string corpId, bool getNewToken = false)
		{
			if (!ProviderTokenContainer.ProviderTokenCollection.ContainsKey(corpId))
			{
				throw new WeixinException("此CorpId尚未注册，请先使用ProviderTokenContainer.Register完成注册（全局执行一次即可）！");
			}
			ProviderTokenBag providerTokenBag = ProviderTokenContainer.ProviderTokenCollection[corpId];
			lock (providerTokenBag.Lock)
			{
				if (getNewToken || providerTokenBag.ExpireTime <= DateTime.Now)
				{
					providerTokenBag.ProviderTokenResult = CommonApi.GetProviderToken(providerTokenBag.CorpId, providerTokenBag.CorpSecret, 10000);
					providerTokenBag.ExpireTime = DateTime.Now.AddSeconds(7200.0);
				}
			}
			return providerTokenBag.ProviderTokenResult;
		}
		public static bool CheckRegistered(string corpId)
		{
			return ProviderTokenContainer.ProviderTokenCollection.ContainsKey(corpId);
		}
	}
}
